package vip.bblog.cunadmin.aopConfig;

import com.google.common.base.Stopwatch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import vip.bblog.cunadmin.common.entity.LoginUser;
import vip.bblog.cunadmin.modules.system.entity.*;
import vip.bblog.cunadmin.modules.system.service.CardService;
import vip.bblog.cunadmin.modules.system.service.CustomerService;
import vip.bblog.cunadmin.modules.system.service.PublisherService;
import vip.bblog.cunadmin.modules.system.service.SysLogService;
import vip.bblog.cunadmin.util.UserUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 日志切面处理类
 *
 * @author Yaming
 * @create 2019-01-24
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    SysLogService sysLogService;
    @Autowired
    CardService cardService;
    @Autowired
    CustomerService customerService;
    @Autowired
    PublisherService publisherService;

    /**
     * 日志切入点
     */
    @Pointcut("@annotation(vip.bblog.cunadmin.aopConfig.Log)")
    public void logPointCut(){}

    @AfterReturning(pointcut = "logPointCut()")
    public void doAfter(JoinPoint joinPoint){
        /**
         * 解析Log注解
         */
        String methodName = joinPoint.getSignature().getName();
        Method method = currentMethod(joinPoint,methodName);
        Log log = method.getAnnotation(Log.class);
        SysLog sysLog = new SysLog();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        sysLog.setCtime(df.format(new Date()));// new Date()为获取当前系统时间
        sysLog.setContent(log.content());
        sysLog.setHandleType(Integer.parseInt(log.handleType()));

        LoginUser loginUser = UserUtils.getLoginUser();
        sysLog.setUsername(loginUser.getUsername()+"【"+loginUser.getNickName()+"】");

        Stopwatch stopwatch = Stopwatch.createStarted();

        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // ip地址
            //String ipAddr = getRemoteHost(request);
            // 请求路径
            String requestUrl = request.getRequestURL().toString();

            // 获取请求参数进行打印
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;

            System.out.println("333333333333333333333333333333");

            System.out.println("44444444444444444444444444444444");

            // 参数名数组
            //String[] parameterNames = ((MethodSignature) signature).getParameterNames();
            // 构造参数组集合项目管理
            List<Object> argList = new ArrayList<>();
            for (Object arg : joinPoint.getArgs()) {
                // 记录操作日志
                if("卡号管理".equals(log.content())){
                    Card b = (Card)arg;
//                    sysLog.setDescription(b.toString());
                    sysLogService.save(sysLog);
                }else if("发行商管理".equals(log.content())){
                    Publisher b = (Publisher)arg;
                    sysLogService.save(sysLog);
                }else if("客户管理".equals(log.content())){
                    Customer b = (Customer)arg;
                    sysLogService.save(sysLog);
                }

                // request/response无法使用toJSON
                if (arg instanceof HttpServletRequest) {
                    argList.add("request");
                } else if (arg instanceof HttpServletResponse) {
                    argList.add("response");
                } else {

                }
            }

            stopwatch.stop();
//            long timeConsuming = stopwatch.elapsed(TimeUnit.MILLISECONDS);
//
//            log.error("请求源IP【{}】 -> 请求URL【{}】\n{} -> {} -> 请求耗时：[{}]毫秒 \n请求参数：{} -> {}\n请求结果：{}",
//                    ipAddr, requestUrl,
//                    className, methodName1, timeConsuming,
//                    JSON.toJSON(parameterNames), JSON.toJSON(argList),
//                    JSON.toJSON(result));
        } catch (Exception e) {

        }

        //保存操作日志

        //logService.put(joinPoint,methodName,log.module(),log.description());
    }

    /**
     * 获取当前执行的方法
     *
     * @param joinPoint  连接点
     * @param methodName 方法名称
     * @return 方法
     */
    private Method currentMethod(JoinPoint joinPoint, String methodName) {
        /**
         * 获取目标类的所有方法，找到当前要执行的方法
         */
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        Method resultMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                resultMethod = method;
                break;
            }
        }
        return resultMethod;
    }

}